<template>
  <div class="container">
    <van-nav-bar title="登录" />
    <van-cell-group>
      <van-field
        label="手机号"
        type="tel"
        v-model.trim="user.mobile"
        placeholder="请输入手机号"
        :error-message="errInfo.mobile"
        required
        clearable
        :rules="[{ required: true, message: '请填写手机号' }]"
      />
      <van-field
        label="密码"
        v-model.trim="user.code"
        type="password"
        placeholder="请输入密码"
        :error-message="errInfo.code"
        required
        clearable
      />
      <div class="btn-wrap">
        <van-button round block type="info" @click="hLogin">登录</van-button>
      </div>
    </van-cell-group>
  </div>
</template>

<script>
// import request from "@/utils/request";
import { login } from '@/api/user'
export default {
  name: 'LoginIndex',
  data () {
    return {
      user: {
        mobile: '13911111111',
        code: '246810'
      },
      errInfo: {
        mobile: '',
        code: ''
      }
    }
  },
  methods: {
    checkInfo (user) {
      if (user.mobile === '') {
        this.errInfo.mobile = '手机号不能为空'
        return false
      } else {
        this.errInfo.mobile = ''
      }
      if (user.code === '') {
        this.errInfo.code = '密码不能为空'
        return false
      } else {
        this.errInfo.code = ''
      }
      return true
    },
    async hLogin () {
      // console.log(this.user)
      // 对用户信息进行验证

      // 1 检测数据有效性
      if (!this.checkInfo(this.user)) {
        return
      }

      // 2 轻提示
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner'
      })

      // request({
      //   method: "POST",
      //   url: "/app/v1_0/authorizations",
      //   data: this.url
      // });
      try {
        const result = await login(this.user)
        console.log(result)
        this.$toast.success('登录成功')
        // 保存信息到vuex
        this.$store.commit('setUser', result.data.data)

        // todo:页面跳转
        const to = this.$route.query.from || '/'
        this.$router.push(to)
      } catch (err) {
        const errMsg = err.response.data.message
        if (errMsg) {
          if (errMsg.mobile) {
            this.$toast.fail('手机号错误')
          }
          if (errMsg.code) {
            this.$toast.fail('密码错误')
          }
        } else {
          this.$toast.fail('登录错误')
        }
      }
    }
  }
}
</script>

<style scoped lang='less'>
.btn-wrap {
  padding: 20px;
}
</style>
